package trss.webapp.action;

import org.springframework.security.core.GrantedAuthority;
import trss.Constants;
import trss.model.Torrent;
import trss.model.User;
import trss.service.TorrentManager;

import javax.faces.context.FacesContext;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * Created by IntelliJ IDEA.
 * User: vfirstov
 * Date: 17.11.2010
 * Time: 15:47:41
 * To change this template use File | Settings | File Templates.
 */
public class TorrentList extends BasePage implements Serializable {

    private static final long serialVersionUID = 973523593757345918L;

    private TorrentManager torrentManager;

    //private boolean isAdmin;

    public TorrentList() {
    }


    public boolean isAdmin() {
        return isUserAdminRole(userManager.getUserByUsername(getRequest().getRemoteUser()));
    }

//    public void setAdmin(boolean admin) {
//        isAdmin = admin;
//    }

    public void setTorrentManager(TorrentManager torrentManager) {
        this.torrentManager = torrentManager;
    }
    
    public List getTorrents() {
        User user = userManager.getUserByUsername(getRequest().getRemoteUser());
        List<Torrent> torrents = isUserAdminRole(user)
                ? torrentManager.getAll() : torrentManager.getTorrents(user, 10);
        return torrents; 
    }

    private boolean isUserAdminRole(User user) {
        Set<GrantedAuthority> roles = user.getAuthorities();
        for (GrantedAuthority role1 : roles) {
            if (role1.getAuthority().equals(Constants.ADMIN_ROLE)) {
                return true;
            }
        }
        return false;
    }

}
